﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Service;
using Icms.WebUI.Builder;
using Icms.WebUI.Dto;
using Omu.Awesome.Mvc;

namespace Icms.WebUI.Controllers
{
    public class CaseController : Cruder<Case, CaseInput>
    {
        private new readonly ICaseService s;

        public CaseController(ICaseService s, IMapper<Case, CaseInput> v) : base(s, v)
        {
            this.s = s;
        }

        public override ActionResult Index()
        {
            return View(new CaseSearchInput());
        }

        public ActionResult Details(Guid? TypeId, Guid? id)
        {
            if(TypeId != null) ViewBag.CaseTypeId = TypeId;
            if (id != null) ViewBag.Case = id.Value.Case();
            return View();
        }

        [HttpPost]
        public virtual ActionResult Search(CaseSearchInput obj, int page = 1, int ps = 5)
        {
            var result = s.GetAll();
            if (obj.TypeId.HasValue) result = result.Where(o => o.TypeId == obj.TypeId);
            if (obj.TypeExamId.HasValue) result = result.Where(o => o.TypeExamId == obj.TypeExamId);
            if (obj.IndexId.HasValue) result = result.Where(o => o.IndexId == obj.IndexId);
            if (obj.CourtId.HasValue) result = result.Where(o => o.CourtId == obj.CourtId);

            if (obj.RegistrationFrom.HasValue && obj.RegistrationTo.HasValue)
                result =
                    result.Where(
                        o => o.CreatedDate >= obj.RegistrationFrom && o.CreatedDate <= obj.RegistrationTo);

            var rows = this.RenderView("rows", result.OrderByDescending(o => o.CreatedDate).Pag(page, ps));

            return Json(new { rows, more = result.Count() > page * ps });
        }

        [ValidateInput(false)]
        public override ActionResult Create(CaseInput o)
        {
            return base.Create(o);
        }

        public override Guid Creation(Case e)
        {
            e.CourtId = Globals.Court().Id;
            return base.Creation(e);
        }
      
        [ValidateInput(false)]
        public override ActionResult Edit(CaseInput o)
        {
            return base.Edit(o);
        }
    }
}